﻿var code_str = "", radarChart = null;
function deviceType() {
    var ua = navigator.userAgent.toLowerCase();
    return ua.indexOf('micromessenger') != -1 ? "WeiXin" : ua.indexOf('android') != -1 ? "Android" : (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1) ? "IOS" : "Web";
};

function codeImg(_canvas) {
    try {
        function drawscreen() {
            _canvas.fillStyle = "#f47a1f";
            _canvas.fillRect(0, 0, 80, 32);
        };
        function write_text(_str) {
            _canvas.fillStyle = "#000000";
            _canvas.font = "20px _sans";
            _canvas.textBaseline = "top";
            _canvas.fillText(_str, 20, 1);
        };
        function getabc() {
            var _str = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9";
            var _str_array = _str.split(",");
            code_str = "";
            for (i = 0; i < 4; i++) {
                var _rnd = Math.floor(Math.random() * _str_array.length);
                code_str += _str_array[_rnd];
            };
        };
        drawscreen();
        getabc();
        write_text(code_str);
    } catch (e) {
    }
}

function setData() {
    var postData = {}, phone = $("#phone").val();
    postData.openid = $("#myopenid").val();
    postData.uname = $("#topheadtxt").html(); // 微信昵称
    postData.headImg = $("#tophead").attr("src"); // 微信头像

    postData.mobilePhone = phone;
    postData.gender = $("input[name='sex']:checked").val() || "";
    postData.birthDate = $("#birthdayValue").val();
    postData.province = $("#provinceID").val();
    postData.city = $("#cityID").val();
    postData.maritalStatus = $("input[name='merry']:checked").val() || "";
    postData.babyAge = $("#age").val();

    var tempInterest = [];
    $.each($("#interest").find("input:checked"), function (index, item) {
        tempInterest.push($(item).val());
    });
    postData.interest = tempInterest.join(',');

    postData.profession = $("#work").val();
    window.localStorage.setItem("qooformdata", JSON.stringify(postData));
    return postData;
}

function initData(res) {
    $("#myopenid").val(res.openid);
    var age = res.babyAge;
    $("#phone").val(res.mobilePhone);
    $("#genderSex input[value='" + res.gender + "']").attr("checked", true);
    $("#birthdayValue").val(res.birthDate);
    $("#provinceID").val(res.province);
    $("#cityID").val(res.city);
    $("#merryContainer input[value='" + res.maritalStatus + "']").attr("checked", true);
    $("#age").val(age).next().html(age == "A" ? "3岁以下" : age == "B" ? "3-6岁" : age == "C" ? "7-12岁" : age == "D" ? "13-15岁" : age == "E" ? "15岁以上" : "请选择");
    $("#work").val(res.profession).next().html($("#workItem>div[data-val='" + res.profession + "']").html());
    var insterVal = res.interest.split(',');
    for (var i = 0; i < insterVal.length; i++) {
        $("#interest input[value='" + insterVal[i] + "']").attr("checked", true);
    }

    $("#tophead").attr("src", res.headImg);
    $("#topheadtxt").html(res.uname);

    //填充日期和城市
    var dateSelectGroup = new DateSelectGroup({
        rowLength: 3,
        $value: $("#birthdayValue"),
        $target: $('#birthday'),
        callback: function () {
        }
    });
    var addressSelectGroup = new AddressSelectGroup({
        rowLength: 2,
        $city: $("#cityID"),
        $province: $("#provinceID"),
        $target: $('#city'),
        callback: function (a) {
        }
    });
}

$(function () {
    var router = new Router({
        container: '#container',
        enterTimeout: 50,
        leaveTimeout: 50
    });

    // 酷兒指数页面
    var qooindex = {
        url: '/qooindex',
        render: function () {
            return $('#tpl_qooindex').html();
        },
        bind: function () {
            $("body").css({ "backgroundColor": "#C5D82E" });
            window.scroll(0, 0);
            document.title = "酷指数 - 酷兒";
            //$(".qoo_index_top .text").html($("body").width() +"-"+ $("body").height());
            radarChart = null;

            setTimeout(function () {

                //取用户数据
                $.ajax({
                    url: '/KrInfoCollection/querytFollowerInfos?apikey=1&passwd=35647&openid=xxx'
                    , type: 'get'
                    , dataType: 'json'
                    , success: function (res) {
                        if (res.status == 200) {
                            $("#qooIndexHead").attr("src", res.datas.headImg);
                            $("#qooIndexNickname").html("昵称："+res.datas.uname);
                        }
                    }
                });

                var gaugeChart = echarts.init(document.getElementById('gaugeChart'));
                // Qoo指数图表   https://github.com/ecomfe/echarts/issues/1284  微信里打开崩溃
                var gaugeOption = {
                    series: [
                        {
                            name: 'Qoo指数',
                            type: 'gauge',
                            startAngle: 180,
                            endAngle: 0,
                            //splitNumber: 0,
                            center: ['50%', '60%'],    // 默认全局居中
                            radius: $("body").width()==320?140:160,
                            axisLine: {            // 坐标轴线
                                lineStyle: {       // 属性lineStyle控制线条样式
                                    color: [[0.2, '#8ED9F9'], [0.8, '#C4D950'], [1, '#F66014']],
                                    width: 180
                                }
                            },
                            axisTick: { show: false },
                            splitLine: { show: false },
                            detail: { show: false },
                            axisLabel: {           // 坐标轴文本标签，详见axis.axisLabel
                                formatter: function (v) {
                                    switch (v + '') {
                                        case '10': return '低';
                                        case '50': return '中';
                                        case '90': return '高';
                                        default: return '';
                                    }
                                },
                                textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                                    color: '#fff',
                                    fontSize: 18,
                                    fontWeight: 'bolder'
                                }
                            },
                            itemStyle: {
                                normal: {
                                    color: "#F9E0CC"
                                }
                            },
                            pointer: {
                                width: 30,
                                length: '80%'
                            },
                            data: [{ value: 0, name: '' }]
                        }
                    ]
                };
                gaugeChart.setOption(gaugeOption);

                //取数据
                $.ajax({
                    url: '/KrInfoCollection/getKooIndex?apikey=1&passwd=35647&openid=xxx'
                    , type: 'get'
                    , dataType: 'json'
                    , success: function (res) {
                        if (res.status == 200) {
                            
                            var all = res.datas.koo_val.toString();

                            gaugeOption.series[0].data[0].value = all;
                            gaugeChart.setOption(gaugeOption, true);

                            //分隔
                            var showValue = [];
                            for (var i = 0, len = all.length; i < len; i++) {
                                showValue.push('<span class="num' + (all[i] == "." ? "dot" : all[i] ) + '"></span>');
                            }
                            $("#qooIndexValue").html(showValue.join(""));

                            radarOption.series[0].data[0].value = [res.datas.active_val, res.datas.trust_val, res.datas.purchase_val, res.datas.share_val];
                            radarChart.setOption(radarOption, true);
                        }
                    }
                });

            }, 500)
        }
    };

    // qoo指数说明
    var qooindexintro = {
        url: '/qooindexintro',
        render: function () {
            return $('#tpl_qooindexintro').html();
        },
        bind: function () {
            window.scroll(0, 0);
            $("body").css({ "backgroundColor": "#FFF5CD" });
            var radarOption = {
                tooltip: {
                    trigger: 'axis'
                },
                polar: [
                    {
                        indicator: [
                            { text: '', max: 100 }, // 活跃指数
                            { text: '', max: 100 }, // 信任指数
                            { text: '', max: 100 }, // 购买指数
                            { text: '', max: 100 }  // 分享指数
                        ],
                        radius: $("body").width() == 320 ? 80 : 88,
                    }
                ],
                series: [
                    {
                        name: 'Qoo指数说明',
                        type: 'radar',
                        itemStyle: {
                            normal: {
                                areaStyle: {
                                    type: 'default'
                                }
                            }
                        },
                        data: [
                            {
                                value: [0, 0, 0, 0],
                                name: '最新数据'
                            }
                        ]
                    }
                ]
            };

            if (!radarChart) {
                radarChart = echarts.init(document.getElementById('radarChart'));
                radarChart.setOption(radarOption);
            }

            //取数据
            $.ajax({
                url: '/KrInfoCollection/getKooIndex?apikey=1&passwd=35647&openid=xxx'
                , type: 'get'
                , dataType: 'json'
                , success: function (res) {
                    if (res.status == 200) {

                        radarOption.series[0].data[0].value = [res.datas.active_val, res.datas.trust_val, res.datas.purchase_val, res.datas.share_val];
                        radarChart.setOption(radarOption, true);
                    }
                }
            });
        }
    };

    // 排行榜页面
    var topdata = {
        url: '/topdata',
        render: function () {
            return $('#tpl_topdata').html();
        },
        bind: function () {
            $("body").css({ "backgroundColor": "#C5D82E" });
            window.scroll(0, 0);
            document.title = "排行榜 - 酷兒";
            setTimeout(function () {

                //排行榜列表
                $.ajax({
                    url: '/KrInfoCollection/getKooIndexRank?apikey=1&passwd=35647&monthId=201601'
                    , type: 'get'
                    , dataType: 'json'
                    , success: function (res) {
                        if (res.status == 200) {
                            var list = [];
                            for (var i = 0, len = res.datas.length; i < len; i++) {
                                list.push('<tr><td>' + res.datas[i].ranknum + '</td><td>' + res.datas[i].uname + '</td><td>' + res.datas[i].koo_val + '</td><td>' + res.datas[i].incr_pct + '</td></tr>');
                            }
                            $("#qooTopDataList").html(list.join(""));
                        } else {
                            $("#qooTopDataMessage").html(res.message || "获取失败");
                        }
                    }
                });

                //排行说明
                $("#qooTopDataIntro").on("click", function () {
                    $("body, .datalist").css({ "overflow": "hidden" });
                    $('#qooTopdataPage').show().on('click', '#qooTopdataClose', function () {
                        $("body, .datalist").css({ "overflow": "auto" });
                        $('#qooTopdataPage').off('click').hide();
                    });
                });

            }, 500)
        }
    };

    // 必须在微信中打开
    var noweixin = {
        url: '/noweixin',
        render: function () {
            return $('#tpl_noweixin').html();
        }
    };

    var xieyi = {
        url: '/xieyi',
        render: function () {
            return $('#tpl_xieyi').html();
        },
        bind: function () {
            window.scroll(0, 0);
        }
    };

    // 完善个人资料
    var form = {
        url: '/form',
        className: 'form',
        render: function () {
            return $('#tpl_form').html();
        },
        bind: function () {
            $("body").css({ "backgroundColor": "#fff5cd" });
            document.title = "完善个人资料 - 酷兒";
            setTimeout(function () {                
                //协议
                $("#agreement").on("click", function () {
                    setData();
                });

                //提交表单
                var validateObj = $("#validateMsg"), loadSubmit = $('#loadingToast'); resultSubmit = $('#toast');
                $("#kooFormBtn").on("click", function () {
                    var postData = {}, phone = $("#phone").val();
                    if (phone != "" && (phone.length != 11 || phone.substring(0, 1) != "1")) {
                        validateObj.find(".weui_toast_content").html("手机号不正确！");
                        validateObj.show();
                        setTimeout(function () {
                            validateObj.hide();
                        }, 2000);
                        return;
                    }

                    // 检查验证码
                    if ($("#codeImg").val() != code_str) {
                        validateObj.find(".weui_toast_content").html("验证码不正确！");
                        validateObj.show();
                        setTimeout(function () {
                            validateObj.hide();
                        }, 2000);
                        return;
                    }

                    postData = setData();

                    // 至少填写一项
                    if (postData.mobilePhone == "" && postData.gender == "" && postData.birthDate == "" && postData.province == "" && postData.maritalStatus == "" && postData.babyAge == "" && postData.interest == "" && postData.profession == "") {
                        validateObj.find(".weui_toast_content").html("请至少输入一项才可以提交资料！");
                        validateObj.show();
                        setTimeout(function () {
                            validateObj.hide();
                        }, 2000);
                        return;
                    }

                    loadSubmit.show();
                    $.ajax({
                        url: '/KrInfoCollection/addFollowerInfo?apikey=1&passwd=35647'
                        , dataType: 'json'
                        , type: 'post'
                        , data: postData
                        , error: function (err) {
                            loadSubmit.hide();
                            validateObj.find(".weui_toast_content").html(err);
                            validateObj.show();
                            setTimeout(function () {
                                validateObj.hide();
                            }, 2000);
                        }
                        , success: function (res) {
                            $("#codeImg").val("");
                            if (res.status == 200) {
                                window.localStorage.removeItem("qooformdata");
                                loadSubmit.hide()
                                resultSubmit.show()
                                setTimeout(function () {
                                    resultSubmit.hide();
                                    window.close();
                                }, 2000);
                            } else {
                                validateObj.find(".weui_toast_content").html(res.message || "提交失败！");
                                validateObj.show();
                                setTimeout(function () {
                                    validateObj.hide();
                                }, 2000);
                            }
                        }
                    });

                });

                //下拉选择
                $(".actionsheetlist").on("click", function () {
                    var _this = this,
                        container = $(_this).next(),
                        mask = container.find('.weui_mask_transition'),
                        weuiActionsheet = container.find('.weui_actionsheet');
                    weuiActionsheet.show().addClass('weui_actionsheet_toggle');
                    mask.show()
                        .focus()//加focus是为了触发一次页面的重排(reflow or layout thrashing),使mask的transition动画得以正常触发
                        .addClass('weui_fade_toggle').one('click', function () {
                            hideActionSheet(weuiActionsheet, mask);
                        });
                    /*container.find('.actionsheet_cancel').one('click', function () {
                        hideActionSheet(weuiActionsheet, mask);
                    });*/

                    mask.unbind('transitionend').unbind('webkitTransitionEnd');

                    //处理选择
                    container.find(".weui_actionsheet_cell").on("click", function () {
                        $(_this).html($(this).html());
                        $(_this).prev().val($(this).attr("data-val"));
                        hideActionSheet(weuiActionsheet, mask);
                    });

                    function hideActionSheet(weuiActionsheet, mask) {
                        weuiActionsheet.removeClass('weui_actionsheet_toggle');
                        mask.removeClass('weui_fade_toggle');
                        mask.on('transitionend', function () {
                            mask.hide();
                            weuiActionsheet.hide()
                        }).on('webkitTransitionEnd', function () {
                            mask.hide();
                            weuiActionsheet.hide()
                        })
                    }

                });

                // 验证码
                var mycanvas = $("#myCodeImg").get(0).getContext("2d");
                codeImg(mycanvas);
                $("#myCodeImg").on("click", function () {
                    codeImg(mycanvas);
                });
                $("#codeImg").on("click", function () {
                    setTimeout(function () {
                        window.scroll(0, $(document).height());
                    },100);
                });
                 $("#phone").on("click", function () {
                    setTimeout(function () {
                        window.scroll(0, $(".koo_form_content").offset().top+65);
                    },100);
                });

                 if (!window.localStorage.getItem("qooformdata")) {

                     //var res = { "datas": { "openid": "", "mobilePhone": "", "birthDate": "", "gender": "", "city": "", "province": "", "babyAge": "", "interest": "", "profession": "", "maritalStatus": "", "uname": "", "headImg": "" }, "useTime": 85, "message": "success", "status": "200" };
                     //initData(res.datas);
                     // 填充数据
                     $.ajax({
                         url: '/KrInfoCollection/querytFollowerInfos?apikey=1&passwd=35647&openid=xxx'
                             , type: 'get'
                             , dataType: 'json'
                             , error: function (err) {
                                 validateObj.find(".weui_toast_content").html(err);
                                 validateObj.show();
                                 setTimeout(function () {
                                     validateObj.hide();
                                 }, 2000);
                             }
                             , success: function (res) {
                                 if (res.status == 200) {
                                     initData(res.datas);
                                 }
                             }
                     });
                 } else {
                     initData(JSON.parse(window.localStorage.getItem("qooformdata")));
                 }

            }, 600);
        }//--end bind
    };

    router.push(noweixin).push(form).push(xieyi).push(qooindex).push(qooindexintro).push(topdata)
        .setDefault((deviceType() == "WeiXin" ? "/qooindex" : "/noweixin"))
        .init();

    if (/Android/gi.test(navigator.userAgent)) {
        window.addEventListener('resize', function () {
            if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
                window.setTimeout(function () {
                    document.activeElement.scrollIntoViewIfNeeded();
                }, 0);
            }
        })
    }
});